﻿using System.Diagnostics;
using System.Globalization;
using System.Threading;
using System.Web.Mvc;
using Ninject;
using nanoCMS.Core.Providers;

namespace nanoCMS.Core.WebProviders {
	public class BasicActionFilter : ActionFilterAttribute
	{
		public WorldContext _worldContext = DependencyResolver.Current.GetService<WorldContext>();
		public BasicActionFilter()
		{
			
			
		}
	
		public override void OnActionExecuting(ActionExecutingContext filterContext)
		{

			//if (filterContext.ActionParameters.ContainsKey("elementKey"))
			//{
			//   string elementKey = filterContext.ActionParameters["elementKey"] as string;
			//   var viewResult = filterContext.Result as ViewResult;
			//   if (viewResult != null)
			//      viewResult.ViewBag.ElementKey = elementKey;
			//}
			
			TenantProvider _tenantProvider = new TenantProvider(_worldContext.Entities);
			if (RequestItems.TenantID == -1)
			{
				int tenantId = _tenantProvider.GetTenantID(filterContext.HttpContext.Request.Url.AbsoluteUri);
				RequestItems.TenantID = tenantId;
			}

			if (RequestItems.TenantLangID == -1)
			{
				RequestItems.TenantLangID = _tenantProvider.Get(RequestItems.TenantID).LangID;
				LanguageProvider languageProvider = new LanguageProvider(_worldContext.Entities);
				var lang = languageProvider.Get(RequestItems.TenantLangID);
				Thread.CurrentThread.CurrentUICulture = new CultureInfo(lang.ShortCode);
			}

			

			base.OnActionExecuting(filterContext);
		}

		public override void OnActionExecuted(ActionExecutedContext filterContext) {

			//var viewResult = filterContext.Result as ViewResult;
			//if (viewResult == null)
			//   base.OnActionExecuted(filterContext);


			//if (elementKey != null)
			//{
			//   filterContext.HttpContext.Response.AddHeader("elementKey", elementKey);
			//   viewResult.ViewBag.ElementKey = elementKey;
			//   elementKey = null;
			//}

			base.OnActionExecuted(filterContext);
		}


	}
}
